# -*- coding: utf-8 -*-
# CreateDate : 2021/12/16 18:45
# Author     : 不肖生
# Github     :
# EditDate   : 
# sourceProj : wxgzh_news
# Description:  信息管理系统接口，通过此接口写入数据
import logging
from urllib.parse import urljoin, quote, urlencode

import requests

from wxgzh_news.constant import Default_User_Agent
from wxgzh_news.settings import BASE_WEBSITE

UserName = "admin"
Password = "123456"


class AddNews:
    def __init__(self):
        # self.url = "http://wuliu.akng.net/admin.php?"
        self.url = urljoin(BASE_WEBSITE, "admin.php?")

        self.PHPSESSID = {"http://isc.chinascm.org.cn": "8563e1e734a892a8c81dff1f6196746c",
                          "http://wuliu.akng.net": "tlnl4837720us069fukodf9n4p"}[BASE_WEBSITE]

        self.headers = {
            "Content-Type": "application/x-www-form-urlencoded",
            "User-Agent": Default_User_Agent,
            "Cookie": self.__login_for_cookie(),
        }

    def add(self, payload: dict):
        """
        :param payload: 添加的内容
        :return:
        """
        response = requests.post(url=self.url, data=payload, headers=self.headers, allow_redirects=False)
        return response

    def __login_for_cookie(self):
        """
        信息管理系统cookie
        :return:
        """
        url = self.url
        payload = {"file": "login", "forward": url, "username": UserName, "password": Password, "submit": "登录",
                   "rmbUser": ""}

        headers = {
            "Content-Type": "application/x-www-form-urlencoded",
            "User-Agent": Default_User_Agent,
            "Cookie": f"PHPSESSID={self.PHPSESSID}; rmbUser=true; userName={UserName}; "
                      f"passWord={Password}; DEH_username={UserName}; DEH_cart=0;"
        }

        response = requests.post(url=url, headers=headers, data=payload, allow_redirects=False)

        cookie_DEH_auth = response.cookies.get("DEH_auth")
        cookie = "PHPSESSID={psid}; rmbUser=true; userName={user}; passWord={pwd}; DEH_auth={DEH_auth}; " \
                 "DEH_username={user}; DEH_cart=0;".format(psid=self.PHPSESSID,
                                                           user=UserName,
                                                           pwd=Password,
                                                           DEH_auth=cookie_DEH_auth)
        return cookie

    @staticmethod
    def upload_pic(remote_url):
        headers = {}
        # headers['content-type'] = "multipart/form-data"
        url = "http://wuliu.akng.net/uploadfile.php"

        remote_url = quote(remote_url, safe="/?=&:")
        data = {
            "from": "photo",
            "remote": remote_url,
        }

        query = f"{url}?{urlencode(data)}"
        try:
            resp = requests.post(query, headers=headers)
        except Exception as e:
            logging.error(f"Upload: {e.args}")
        else:
            try:
                image_url = resp.json()['url']
            except Exception as e:
                logging.error(f"{url}: {e.args}")
            else:
                return image_url